package com.dycong.common.threadUtil;

import lombok.experimental.Delegate;

import javax.annotation.PreDestroy;
import java.util.concurrent.*;

/**
 * Created by dycong on 2016/11/16.
 */
// TODO: 2016/11/17 这些都需要在main()方法运行，创建POOL实例，Junit是单元测试，不适合在这里测试，不靠谱，处理不好关联关系吧？！
public class ScheduledThreadPool {


    public static final int DEFAULT_SIZE = 10;

    @Delegate
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(DEFAULT_SIZE);


    @PreDestroy
    public void destroy() {
        scheduledExecutorService.shutdown();
    }

    //在main方法有效
    public void test()throws Exception {
         ScheduledThreadPool scheduledThreadPool=new ScheduledThreadPool();
        final Runnable myRunnable = new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "---testFuture-Runnable");
            }
        };

        final Runnable timer = new Runnable() {
            @Override
            public void run() {
                throw new RuntimeException();
            }
        };

        Callable<Integer> myCallable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println(Thread.currentThread().getName() + "---testFuture");
                return null;
            }
        };

        FutureTask task = new FutureTask(myRunnable, "");
          /*@see 可做定时器*/
//        scheduledExecutorService.scheduleWithFixedDelay(timer, 10 * 5, 10, TimeUnit.MILLISECONDS);

        try {
            Thread.sleep(3000);
        } catch (Exception e) {
            throw e;
        }

        scheduledExecutorService.scheduleWithFixedDelay(myRunnable, 1000 * 1, 1000 * 1, TimeUnit.MILLISECONDS);
        /*@see 使用Future只会执行一次，不会循环*/
        scheduledExecutorService.scheduleWithFixedDelay(task, 1000 * 1, 1000 * 1, TimeUnit.MILLISECONDS);
    }

    public static void main(String[] args) {
        ScheduledThreadPool threadPool = new ScheduledThreadPool();
        try {
            threadPool.test();
        } catch (Exception e) {
            System.out.println("---" + e);
        }
    }
}


